package com.zdsoft.site.mina.client;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.util.ReferenceCountingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MinaTimeClient {
    private static Logger logger=LoggerFactory.getLogger(MinaTimeClient.class);
    private static NioSocketConnector connector = new NioSocketConnector();
    
    public static void main(String[] args){
        // 创建客户端连接器.
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("codec", 
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        //自定义过滤器
        connector.getFilterChain().addLast("minaTimeFilter", new ReferenceCountingFilter(new MinaTimeFilter()));
        // 设置连接超时检查时间
        connector.setConnectTimeoutCheckInterval(30);
        connector.setHandler(new TimeClientHandler());
        // 建立连接
        ConnectFuture cf = connector.connect(new InetSocketAddress("localhost", 6488));
//        // 等待连接创建完成(变异步为同步)
//        cf.awaitUninterruptibly();
//        cf.getSession().write("Hi Server!");
//        cf.getSession().write("quit");
//        // 等待连接断开
//        cf.getSession().getCloseFuture().awaitUninterruptibly();
//        // 释放连接
//        connector.dispose();
        
        cf.addListener(new IoFutureListener<ConnectFuture>() {
			@Override
			public void operationComplete(ConnectFuture future) {
				IoSession session=future.getSession();
				logger.debug("获取连接对应的session={}",session.getId());
				session.write("Hi Server!");
				session.write("quit");				
				logger.debug("数据发送完毕");
			}
		});
        logger.debug("客户代码全部执行完毕,但异步结果还在执行");
    }
}